package com.chuangjiangx.member.basic.web.exceptionhandler;

import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义异常处理
 * @author caoquanlong
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 基于@ExceptionHandler异常处理.
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Response exceptionHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Throwable throwable) {
        logger.error("请求路径:{},出现异常:{}", request.getRequestURI() ,throwable);
        if (throwable instanceof BaseException) {
            BaseException ex = (BaseException) throwable;
            return ResponseUtils.error(ex.getErrCode(), ex.getErrMessage());
        } else if (throwable instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException mane = (MethodArgumentNotValidException) throwable;
            BindingResult bindingResult = mane.getBindingResult();
            return ResponseUtils.error("-1", bindingResult.getAllErrors().get(0).getDefaultMessage());
        } else if (throwable instanceof BindException) {
            BindException bindException = (BindException) throwable;
            BindingResult bindingResult = bindException.getBindingResult();
            return ResponseUtils.error("-1", bindingResult.getAllErrors().get(0).getDefaultMessage());
        } else if (throwable instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException ex = (MissingServletRequestParameterException) throwable;
            return ResponseUtils.error("-1", "参数缺失：" + ex.getParameterName());
        } else if (throwable instanceof IllegalArgumentException) {
            return ResponseUtils.error("-1", throwable.getMessage());
        } else if (throwable instanceof HttpMessageNotReadableException) {
            return ResponseUtils.error("-1", "http请求的body为空！");
        } else {
            String msg = throwable.getMessage();
            if (msg.length() > 50) {
                return ResponseUtils.error("-1", "服务端发生错误！");
            } else {
                return ResponseUtils.error("-1", throwable.getMessage());
            }
        }
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object noHandlerFoundException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        return ResponseUtils.error("404", "访问路径不存在");
    }

}
